import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {FormGroup, FormControl, Validators, FormBuilder} from '@angular/forms';
import { Md5 } from 'ts-md5/dist/md5';

import {AuthService} from '../services/auth.service';
import {ToastComponent} from '../shared/toast/toast.component';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  date: any = new Date();
  timestamp = Date.parse(this.date) / 1000;
  system_type = 1;
  key = btoa(this.timestamp + '-' + 'VtWeb');

  loginForm: FormGroup;
  username = new FormControl('', [
    Validators.required,
    Validators.minLength(5),
    Validators.maxLength(20)
  ]);
  password = new FormControl('', [
    Validators.required,
    Validators.minLength(6)
  ]);

  usernameInputFocus = false;
  passwordInputFocus = false;

  setUsernameInputFocus() {
    this.usernameInputFocus = true;
  }

  setUsernameInputBlur() {
    this.usernameInputFocus = false;
  }

  setPasswordInputFocus() {
    this.passwordInputFocus = true;
  }

  setPasswordInputBlur() {
    this.passwordInputFocus = false;
  }

  constructor(private auth: AuthService,
              private formBuilder: FormBuilder,
              private router: Router,
              public toast: ToastComponent) {
  }

  ngOnInit() {
    this.toast.setMessage('', '');

    if (this.auth.loggedIn) {
      this.router.navigate(['/']);
    }
    this.loginForm = this.formBuilder.group({
      username: this.username,
      password: this.password,
      system_type: this.system_type,
      timestamp: this.timestamp,
      key: this.key
    });
  }

  setClassUsername() {
    return !this.username.pristine && !this.username.valid;
  }

  setClassPassword() {
    return !this.password.pristine && !this.password.valid;
  }

  login() {
    this.loginForm.value.password = Md5.hashStr(this.loginForm.value.password);
    this.auth.login(this.loginForm.value).subscribe(
      res => {
        if (res.code === '1000') {
          this.router.navigate(['/admin/dashboard']);
        } else {
          this.toast.setMessage('invalid email or password!', 'danger');
        }
      }
    );
  }
}
